package dal

import (
	"github.com/gin-gonic/gin"
	"honghu_be/dal/po"
)

func CreateAd(c *gin.Context, ad *po.Ad) error {
	sql := GetDB().Model(&po.Ad{})
	return sql.Create(ad).Error
}

func DeleteAd(c *gin.Context, adId int) error {
	sql := GetDB().Model(po.Ad{})
	return sql.Delete(po.Ad{}, adId).Error
}

type GetAdRequest struct {
	AdId   int
	Limit  int
	Offset int
}

func GetAds(c *gin.Context, req *GetAdRequest) ([]*po.Ad, error) {
	var pos []*po.Ad
	sql := GetDB().Model(po.Ad{})
	if req.AdId != 0 {
		sql = sql.Where("id = ?", req.AdId)
	}
	if req.Limit > 0 {
		sql = sql.Limit(req.Limit)
	} else {
		sql = sql.Limit(1)
	}
	if req.Offset > 0 {
		sql = sql.Offset(req.Offset)
	}
	sql = sql.Order("count desc")
	sql = sql.Find(&pos)
	return pos, sql.Error
}

func UpdateAd(c *gin.Context, adId int, adPo *po.Ad) error {
	sql := GetDB().Model(po.Ad{})
	sql = sql.Where("id = ?", adId)
	err := sql.Updates(adPo).Error
	if err != nil {
		return err
	}
	sql.First(adPo)
	return nil
}
